package com.klikmee.sms.core.base.communicator.telenor.longsms;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import com.klikmee.sms.core.ws.telenor.client.receivesms.SmsTypeExt;

public class TelenorLongSMSWrapper extends Observable {
	// whole message to be returned to communicator
	private SmsTypeExt			rowMessage;

	// list of message bodies in this long SMS. List is used because is possible that
	// all parts do not come in sequence and their order can be mixed up.
	// so messages are inserted into the list by their sequence numbers.
	private List<String>		messageParts	= new ArrayList<String>();

	// long sms parameters used to track message state

	private int					totalparts		= 0;
	private int					partsReceived	= 0;
	private String				messageId		= null;

	// initializes long SMS message and and submits initial part of message for processing  
	public TelenorLongSMSWrapper( SmsTypeExt rowMessage, int totalParts, String messageId) {
		super();
		this.rowMessage = rowMessage;

		// init total number of parts
		this.totalparts = totalParts;
		this.messageId = messageId;
	}

	public void submitPart( int sequenceNumber, String messageText) {
		// submit new message body to extractor
		
		// get message squence number
		// insert current message part into the list
		messageParts.add( sequenceNumber - 1, messageText ); // sequence number starts from 1 so we decrease it by 1

		// increase number of receivded parts
		partsReceived++;

		// if this is the last part, all message parts should be concatenated and SMS joiner should be notified
		if (totalparts == partsReceived) {
			// concatenate all parts and set result as a row message object text
			String wholeText = "";
			for (String listElement : messageParts) {
				wholeText += listElement;
			}

			rowMessage.setMessage( wholeText );
			
			// notify any observers that message is complete and send the row SMS object as param for further processing
			setChanged();
			notifyObservers( this.rowMessage );
		}

	}
	
	public String getMessageId() {
		return messageId;
	}
}
